package com.midcent.leakcanarylibrary;

import android.app.Application;

import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;


/**
 * @作者 zx
 * @创建时间 2018/3/20
 * @描述 内存泄漏LeakCanary插件管理类，用于管理LeakCanary插件
 * @修改时间 2018/3/20
 * @修改描述 内存泄漏LeakCanary插件管理类，用于管理LeakCanary插件
 * @修改者 zx
 **/
public class LeakCanaryManager {

    private LeakCanaryManager() {

    }

    private static class Singleton {
        private static LeakCanaryManager instance = new LeakCanaryManager();
    }

    public static LeakCanaryManager getInstance() {
        return Singleton.instance;
    }

    private RefWatcher refWatcher = null;
    private Application mApplication = null;

    /**
     * 初始化内存泄漏检查
     */
    public void initLeakCanary(Application application) {
        if (this.mApplication != null) {
            throw new RuntimeException("LeakCanary can init only once!");
        }
        this.mApplication = application;
        if (LeakCanary.isInAnalyzerProcess(mApplication)) {//1
            // This process is dedicated to LeakCanary for heap analysis.
            // You should not init your app in this process.
            return;
        }
        this.refWatcher = setupLeakCanary();
    }

    /**
     * 初始化RefWatcher
     *
     * @return
     */
    private RefWatcher setupLeakCanary() {
        if (mApplication == null) {
            throw new RuntimeException("application is null!");
        }
        if (LeakCanary.isInAnalyzerProcess(mApplication)) {
            return RefWatcher.DISABLED;
        }
        return LeakCanary.install(mApplication);
    }

    /**
     * 获取RefWatcher
     *
     * @return
     */
    public RefWatcher getRefWatcher() {
        if (refWatcher == null) {
            throw new RuntimeException("refWatcher is null!");
        }
        return refWatcher;
    }

}
